//
//  LeiJiXiaoShouEViewController.m
//  FactorySale
//
//  Created by 李 on 2020/1/13.
//  Copyright © 2020 主事丫环. All rights reserved.
//  累计销售额

#import "LeiJiXiaoShouEViewController.h"
#import "LeiJiXiaoShouEListTopCell.h"
#import "LeiJiXiaoShouEListMiddleCell.h"
#import "LeiJiXiaoShouEListBottomCell.h"
#import "LeiJiXiaoShouEListModel.h"
#import "LeiJiXiaoShouEDetailViewController.h"
#import "PGDatePickManager.h"//日期选择控件

@interface LeiJiXiaoShouEViewController ()<UITableViewDelegate,UITableViewDataSource,PGDatePickerDelegate>
//列表
@property (nonatomic,strong) UITableView *listTableView;
@property (nonatomic,strong) NSMutableArray *listArray;
@property (nonatomic,strong)NSString *startTime;
@property (nonatomic,strong)NSString *endTime;

@property (nonatomic,strong)UILabel *startTimeLab;
@property (nonatomic,strong)UILabel *endTimeLab;
@property(nonatomic,strong)UIView *bgview;
@property(nonatomic,assign)BOOL isleft;
@property(nonatomic,assign)UILabel *moenylab;
@end

static NSString *const LeiJiXiaoShouEListTopCellID = @"LeiJiXiaoShouEListTopCell";
static NSString *const LeiJiXiaoShouEListMiddleCellID = @"LeiJiXiaoShouEListMiddleCell";
static NSString *const LeiJiXiaoShouEListBottomCellID = @"LeiJiXiaoShouEListBottomCell";

@implementation LeiJiXiaoShouEViewController
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"累计销售额";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = Main_BackGroundColor;
    [self addBackTableView];
    [self requestSalesVolume];
    
}
-(void)requestSalesVolume
{
    //2020-001-01
    NSString *begTime = self.startTime;
    NSString *endTime = self.endTime;
    
    
    
    if (!strIsEmpty(begTime)) {
        
        NSArray *array = [begTime componentsSeparatedByString:@"-"];
        NSString *monthStr = array[1];
        NSString *dayStr = array[2];
        if (monthStr.length < 2) {
            NSMutableString* str1=[[NSMutableString alloc]initWithString:begTime];//存在堆区，可变字符串
            [str1 insertString:@"0"atIndex:5];//把一个字符串插入另一个字符串中的某一个位置
            KMyLog(@"dsfdsfds%@",str1);
            begTime = str1;
        }
        
        if (dayStr.length < 2) {
            NSMutableString* ind2=[[NSMutableString alloc]initWithString:begTime];//存在堆区，可变字符串
            [ind2 insertString:@"0"atIndex:8];//把一个字符串插入另一个字符串中的某一个位置
            KMyLog(@"dsfdsfds%@",ind2);
            begTime = ind2;
        }
    }else
    {
        ShowToastWithText(@"请选择开始时间");
    }
    
    if (!strIsEmpty(endTime)) {
        
        NSArray *array = [endTime componentsSeparatedByString:@"-"];
        NSString *monthStr = array[1];
        NSString *dayStr = array[2];
        if (monthStr.length < 2) {
            NSMutableString* str1=[[NSMutableString alloc]initWithString:endTime];//存在堆区，可变字符串
            [str1 insertString:@"0"atIndex:5];//把一个字符串插入另一个字符串中的某一个位置
            KMyLog(@"dsfdsfds%@",str1);
            endTime = str1;
        }
        
        if (dayStr.length < 2) {
            NSMutableString* ind2=[[NSMutableString alloc]initWithString:endTime];//存在堆区，可变字符串
            [ind2 insertString:@"0"atIndex:8];//把一个字符串插入另一个字符串中的某一个位置
            KMyLog(@"dsfdsfds%@",ind2);
            endTime = ind2;
        }
    }else
    {
        ShowToastWithText(@"请选择结束时间");
    }
    
    if ([begTime stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue>[endTime stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue) {
        
        ShowToastWithText(@"结束时间不能小于开始时间");
        self.endTimeLab.text = nil;
        self.endTime = nil;
        return;
    }
    
    
    self.startTimeLab.text = begTime;
    self.endTimeLab.text = endTime;
    NSDictionary *param = @{
        @"begTime":NOTNIL(begTime),
        @"endTime":NOTNIL(endTime),
    };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTool POST:salesVolume param:param success:^(id dic) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.listArray = [LeiJiXiaoShouEListModel mj_objectArrayWithKeyValuesArray:dic[@"data"][@"parts"]];
        [self.listTableView reloadData];
        
        self.moenylab.text = [NSString stringWithFormat:@"%@元",dic[@"data"][@"allAmount"]];
        
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:NO];
}
-(void)addBackTableView
{
    [self addHeaderView];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LeiJiXiaoShouEListTopCell class]) bundle:nil] forCellReuseIdentifier:LeiJiXiaoShouEListTopCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LeiJiXiaoShouEListMiddleCell class]) bundle:nil] forCellReuseIdentifier:LeiJiXiaoShouEListMiddleCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LeiJiXiaoShouEListBottomCell class]) bundle:nil] forCellReuseIdentifier:LeiJiXiaoShouEListBottomCellID];
    
    [self.view addSubview:self.listTableView];
    
    
}
- (UITableView *)listTableView
{
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,kNaviHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kNaviHeight) style:UITableViewStylePlain];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _listTableView.estimatedSectionHeaderHeight = 0;
        _listTableView.estimatedSectionFooterHeight = 0;
        _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTableView.backgroundColor =  Main_BackGroundColor;
    }
    return _listTableView;
}
#pragma mark UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 10;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.01;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headerView.backgroundColor = Main_BackGroundColor;
    return headerView;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 0.5)];
    headerView.backgroundColor = Main_BackGroundColor;
    return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return 3;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0) {
        return 82;
    }
    else if (indexPath.row ==1) {
        return 41;
    }
    else if (indexPath.row ==2) {
        return 57;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        LeiJiXiaoShouEListModel *model = [LeiJiXiaoShouEListModel mj_objectWithKeyValues:[self.listArray safeObjectAtIndex:indexPath.section]];
        LeiJiXiaoShouEListTopCell *cell = [tableView dequeueReusableCellWithIdentifier:LeiJiXiaoShouEListTopCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }
    if (indexPath.row==1) {
        
        LeiJiXiaoShouEListModel *model = [LeiJiXiaoShouEListModel mj_objectWithKeyValues:[self.listArray safeObjectAtIndex:indexPath.section]];
        LeiJiXiaoShouEListMiddleCell *cell = [tableView dequeueReusableCellWithIdentifier:LeiJiXiaoShouEListMiddleCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }
    if (indexPath.row==2) {
        
        LeiJiXiaoShouEListBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:LeiJiXiaoShouEListBottomCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.lookDetailBtn addTarget:self action:@selector(lookDetailBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    NSString *cellIdentifier = @"iden3";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    return cell;
    
}

-(void)addHeaderView
{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = Main_BackGroundColor;
    headerView.frame = CGRectMake(10, 10, KWIDTH-20, 185);
    
    UIImageView *greenImage = [[UIImageView alloc] init];
    greenImage.frame = CGRectMake(10, 7, KWIDTH-20, 106);
    greenImage.image = imgname(@"timeBack");
    greenImage.userInteractionEnabled = YES;
    
    //开始时间
    UIView *backView1 = [[UIView alloc] init];
    backView1.backgroundColor = [UIColor clearColor];
    backView1.frame = CGRectMake(0, 0, KWIDTH-20, 106/2);
    [greenImage addSubview:backView1];
    backView1.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startTimeClick)];
    [backView1 addGestureRecognizer:tap1];
    
    UILabel *wordsLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 23.5, 100, 14)];
    wordsLab.font = KFontPingFangSCMedium(14);
    wordsLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
    wordsLab.text = @"开始时间";
    [backView1 addSubview:wordsLab];
    wordsLab.userInteractionEnabled = YES;
    
    NSString *currentTime = [self getCurrentTimeWithFormatter];//当前日期
    NSString *firstDateStr = [HFTools getFirstDayOfThisMonth];//月初第一天
    
    UILabel *startTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH-20-38-200, 23.5, 200, 14)];
    startTimeLab.font = KFontPingFangSCMedium(14);
    startTimeLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
    startTimeLab.textAlignment = NSTextAlignmentRight;
    startTimeLab.userInteractionEnabled = YES;
    [backView1 addSubview:startTimeLab];
    self.startTimeLab = startTimeLab;
    self.startTime = firstDateStr;
    self.startTimeLab.text = firstDateStr;
    
    UIImageView *arrowImage = [[UIImageView alloc] init];
    arrowImage.frame = CGRectMake(KWIDTH-20-20-5.5, startTimeLab.top, 5.5, 10.5);
    arrowImage.image = imgname(@"arrow");
    [backView1 addSubview:arrowImage];
    arrowImage.userInteractionEnabled = YES;
    [greenImage addSubview:backView1];
    //line
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor whiteColor];
    line.frame = CGRectMake(0, 106/2-0.5, KWIDTH-20,0.5);
    [greenImage addSubview:line];
    
    //结束时间
    UIView *backView2 = [[UIView alloc] init];
    backView2.backgroundColor = [UIColor clearColor];
    backView2.frame = CGRectMake(0, 106/2, KWIDTH-20, 106/2);
    [greenImage addSubview:backView2];
    
    [headerView addSubview:greenImage];
    
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endTimeClick)];
    [backView2 addGestureRecognizer:tap2];
    
    UILabel *wordsLab2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 14.5, 100, 14)];
    wordsLab2.font = KFontPingFangSCMedium(14);
    wordsLab2.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
    wordsLab2.text = @"结束时间";
    [backView2 addSubview:wordsLab2];
    
    UILabel *endTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(KWIDTH-20-38-200, 14.5, 200, 14)];
    endTimeLab.font = KFontPingFangSCMedium(14);
    endTimeLab.textColor =[UIColor colorWithHexString:@"#FFFFFF"];
    endTimeLab.textAlignment = NSTextAlignmentRight;
    [backView2 addSubview:endTimeLab];
    self.endTimeLab = endTimeLab;
    self.endTime = currentTime;
    self.endTimeLab.text = currentTime;
    
    UIImageView *arrowImage2 = [[UIImageView alloc] init];
    arrowImage2.frame = CGRectMake(KWIDTH-20-20-5.5, endTimeLab.top, 5.5, 10.5);
    arrowImage2.image = imgname(@"arrow");
    [backView2 addSubview:arrowImage2];
    
    
    UIImageView *backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, greenImage.bottom, ScreenW-30, 75)];
    backImageView.image = [UIImage imageNamed:@"xiaoShouE"];
    [headerView addSubview:backImageView];
    
    UILabel *wordlab = [[UILabel alloc]initWithFrame:CGRectMake(24, 37, 70, 12)];
    wordlab.font = FontSize(12);
    wordlab.textColor = [UIColor whiteColor];
    wordlab.text = @"累计销售额";
    wordlab.textAlignment = NSTextAlignmentCenter;
    [backImageView addSubview:wordlab];
    
    UILabel *moenylab = [[UILabel alloc]initWithFrame:CGRectMake(wordlab.right, 35, 200, 18)];
    moenylab.font = FontSize(18);
    moenylab.textColor = [UIColor whiteColor];
    moenylab.text = @"";
    moenylab.textAlignment = NSTextAlignmentLeft;
    [backImageView addSubview:moenylab];
    self.moenylab = moenylab;
    
    self.listTableView.tableHeaderView = headerView;
    
}
-(void)startTimeClick
{
    self.isleft = YES;
    [self showbgview];
}
-(void)endTimeClick
{
    self.isleft = NO;
    [self showbgview];
}
-(void)showbgview
{
    
    self.bgview = [[UIView alloc]initWithFrame:CGRectMake(0, kNaviHeight, KWIDTH, KHEIGHT)];
    self.bgview.backgroundColor = RGBA(1, 1, 1, 0.5);
    [self.view addSubview:_bgview];
    
    UIView *whithview = [[UIView alloc]initWithFrame:CGRectMake(0, KHEIGHT-kNaviHeight-331, KWIDTH, 331)];
    whithview.backgroundColor = [UIColor whiteColor];
    [self.bgview  addSubview:whithview];
    
    UIView *uobg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 41)];
    uobg.backgroundColor = [UIColor whiteColor];
    [whithview  addSubview:uobg];
    
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackground = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    // 控制显示分割线的属性
    //    datePicker.datePickerType = PGDatePickerTypeVertical;
    datePicker.isHiddenMiddleText = false;
    datePicker.textColorOfSelectedRow = zhutiColor;
    datePicker.lineBackgroundColor = [UIColor colorWithHexString:@"#DBDBDB"];
    
    datePicker.maximumDate = [NSDate date];
    datePicker.autoSelected = true;
    datePicker.datePickerMode = PGDatePickerModeDate;
    [whithview addSubview:datePickManager.view];
    datePickManager.view.frame = CGRectMake(0, 41, KWIDTH, KHEIGHT);
    [self addChildViewController:datePickManager];
    
    UIButton *fifishBUt = [UIButton  buttonWithType:(UIButtonTypeCustom)];
    [fifishBUt setTitle:@"确认" forState:(UIControlStateNormal)];
    [whithview addSubview:fifishBUt];
    fifishBUt.titleLabel.font =  KFontPingFangSCMedium(14);
    [fifishBUt setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    [fifishBUt addTarget:self action:@selector(finishAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [fifishBUt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.right.offset(-16);
        make.width.offset(40);
        make.height.offset(22);
    }];
    
    UIButton *quxiaoBUt = [UIButton  buttonWithType:(UIButtonTypeCustom)];
    [quxiaoBUt setTitle:@"取消" forState:(UIControlStateNormal)];
    [whithview addSubview:quxiaoBUt];
    quxiaoBUt.titleLabel.font =  KFontPingFangSCMedium(14);
    [quxiaoBUt setTitleColor:zhutiColor forState:(UIControlStateNormal)];
    [quxiaoBUt addTarget:self action:@selector(quxiaoAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [quxiaoBUt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.left.offset(16);
        make.width.offset(40);
        make.height.offset(22);
    }];
    
}
-(void)quxiaoAction:(UIButton *)but{
    self.startTime = [HFTools getFirstDayOfThisMonth];//月初第一天;
    self.endTime = [self getCurrentTimeWithFormatter];//当前日期;
    [self.bgview removeFromSuperview];
}

-(void)finishAction:(UIButton *)buf {
    
    [self.bgview removeFromSuperview];
    
    if (self.isleft) {
        self.startTimeLab.text = self.startTime;
        
    }else{
        self.endTimeLab.text = self.endTime;
    }
    [self requestSalesVolume];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents {
    NSString *time = [NSString stringWithFormat:@"%ld-%ld-%ld",dateComponents.year,dateComponents.month,dateComponents.day];
    if (self.isleft) {
        self.startTime = time;
        
    }else{
        self.endTime = time;
    }
}

//获取当前时间
- (NSString *)getCurrentTimeWithFormatter {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}
-(void)lookDetailBtnClick:(UIButton *)button
{
    LeiJiXiaoShouEListBottomCell *cell = (LeiJiXiaoShouEListBottomCell *)[[button superview] superview];
    NSIndexPath *indexPath = [_listTableView indexPathForCell:cell];
    LeiJiXiaoShouEListModel *model = [LeiJiXiaoShouEListModel mj_objectWithKeyValues:[self.listArray safeObjectAtIndex:indexPath.section]];
    
    LeiJiXiaoShouEDetailViewController *vc = [[LeiJiXiaoShouEDetailViewController alloc]init];
    vc.id = model.id;
    vc.begTime = self.startTimeLab.text;
    vc.endTime = self.endTimeLab.text;
    [self.navigationController pushViewController:vc animated:YES];
    
}
@end
